package com.oocl.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.oocl.dao.UserDao;
import com.oocl.pojo.User;
import com.oocl.util.DBUtil;

public class UserDaoImpl implements UserDao{

	public int addUser(User user) {
		Connection connection  = null;
		connection = DBUtil.getConnection();
		PreparedStatement ps = null;
		String sql = "insert into userinfo(id,uname,salary,birth_date,sex,headImage) values(seq_u1.nextval,?,?,?,?,?)";
		int n=0;
		try {
			ps = connection.prepareStatement(sql);
			ps.setString(1, user.getUsername());
			ps.setDouble(2, user.getSalary());
			ps.setDate(3, new Date(user.getBirthDate().getTime()));
			ps.setBoolean(4, user.isSex());
			ps.setBytes(5, user.getHeadImage());
			n = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			DBUtil.release(null, ps, connection);
		}
		return n;
	}

	public List<User> findAll() {
		Connection connection  = null;
		connection = DBUtil.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		String sql = "select * from userinfo";
		List<User> users = new ArrayList<User>();
		User user = null;
		try {
			ps = connection.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				user = new User();
				user.setId(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setSalary(rs.getDouble(3));
				user.setBirthDate(new java.util.Date(rs.getDate(4).getTime()));
				user.setSex(rs.getBoolean(5));
				user.setHeadImage(rs.getBytes(6));
				users.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return users;
	}

}
